"""
Case Type   : ubtree页面解析工具
Case Name   : pagehack -t指定ubtree_index_哈希分区表
Create At   : 2025-10-24
Owner       : sungang14
Description :
    1、创建ustore哈希分区表
    2、创建rcr索引
    3、插入测试数据
    4、查询索引文件路径
    5、解析索引页面
Expect      :
    1、设置成功
    2、成功
    3、成功
    4、成功
    5、解析索引页面成功
History     :
"""

import os
import time
import unittest
from yat.test import Node
from yat.test import macro
from testcase.utils.CommonSH import CommonSH
from testcase.utils.Constant import Constant
from testcase.utils.Logger import Logger

logger = Logger()


class SlowSQLTestCase(unittest.TestCase):
    def setUp(self):
        logger.info(f'-----{os.path.basename(__file__)} start-----')
        self.constant = Constant()
        self.comsh = CommonSH('PrimaryDbUser')
        self.userNode = Node('PrimaryDbUser')
        self.table_name = f"t_ubtree_pagehack_0014"
        self.index_name = f"i_ubtree_pagehack_0014"
        self.prepare_data_00 = f"drop table if exists {self.table_name} cascade;"
        self.prepare_data_01 = f"""create table {self.table_name} (
                                        id bigint primary key,
                                        region varchar(20),
                                        city varchar(20),
                                        sales numeric(10,2),
                                        create_time timestamp
                                        ) with (storage_type=ustore)
                                        partition by hash(city) (
                                            partition p1,
                                            partition p2,
                                            partition p3
                                    );"""
        self.prepare_data_02 = f"create index {self.index_name} on {self.table_name} using ubtree(city) local with (index_type='rcr');"
        self.prepare_data_03 = f"""insert into {self.table_name} (id, region, city, sales, create_time)
                                    select
                                    n,
                                    case n % 5
                                    when 0 then 'east'
                                    when 1 then 'west'
                                    when 2 then 'north'
                                    when 3 then 'south'
                                    else 'region_' || (n % 10)
                                    end as region,
                                    case
                                    when n % 10 = 0 then 'beijing'
                                    when n % 10 = 1 then 'shanghai'
                                    when n % 10 = 2 then 'guangzhou'
                                    when n % 10 = 3 then 'shenzhen'
                                    else 'city_' || (n % 100)
                                    end as city,
                                    (random() * 5000 + 500)::numeric(10,2),
                                    now() - (n * interval '1 day')
                                    from generate_series(1, 1000) as n;
                                    select 'p1' as partition, count(*) from {self.table_name} partition (p1)
                                    union all
                                    select 'p2', count(*) from {self.table_name} partition (p2)
                                    union all
                                    select 'p3', count(*) from {self.table_name} partition (p3);"""
        self.prepare_data_04 = f"SELECT pg_relation_filepath('{self.index_name}');"
        self.prepare_data_05 = f"select relname, relfilenode from pg_partition where parentid = (select oid from pg_class where relname = '{self.index_name}');"

    def test_slowsql(self):
        text = '--step1:创建ustore哈希分区表;expect:成功--'
        logger.info(text)
        data_cmd = self.comsh.execut_db_sql(self.prepare_data_00)
        logger.info(data_cmd)
        self.assertIn(self.constant.TABLE_DROP_SUCCESS, data_cmd, '执行失败' + text)
        data_cmd = self.comsh.execut_db_sql(self.prepare_data_01)
        logger.info(data_cmd)
        self.assertIn(self.constant.TABLE_CREATE_SUCCESS, data_cmd, '执行失败' + text)

        text = '--step2:创建ubtree索引;expect:成功--'
        logger.info(text)
        data_cmd = self.comsh.execut_db_sql(self.prepare_data_02)
        logger.info(data_cmd)
        self.assertIn(self.constant.CREATE_INDEX_SUCCESS_MSG, data_cmd, '执行失败' + text)

        text = '--step3:插入测试数据;expect:成功--'
        logger.info(text)
        data_cmd = self.comsh.execut_db_sql(self.prepare_data_03)
        logger.info(data_cmd)
        self.assertIn(f"INSERT 0 1000", data_cmd, '执行失败' + text)
        self.assertIn(f"p1        |   180", data_cmd, '执行失败' + text)
        self.assertIn(f"p2        |   310", data_cmd, '执行失败' + text)
        self.assertIn(f"p3        |   510", data_cmd, '执行失败' + text)

        text = '--step4:查询索引文件路径;expect:成功--'
        logger.info(text)
        time.sleep(5)
        data_cmd = self.comsh.execut_db_sql(self.prepare_data_04)
        logger.info(data_cmd)
        self.assertIn(f"1 row", data_cmd, '执行失败' + text)
        res_path = data_cmd.splitlines()[-2].strip()
        logger.info(res_path)
        data_cmd5 = self.comsh.execut_db_sql(self.prepare_data_05)
        logger.info(data_cmd5)
        self.assertIn(f"p1_city_idx", data_cmd5, '执行失败' + text)
        self.assertIn(f"p2_city_idx", data_cmd5, '执行失败' + text)
        self.assertIn(f"p3_city_idx", data_cmd5, '执行失败' + text)
        for i in range(-4, -1, 1):
            res_path_st = os.path.join(os.path.dirname(res_path), data_cmd5.splitlines()[i].split('|')[1].strip())
            logger.info(res_path_st)

            text = '--step5:解析索引文件;expect:成功--'
            logger.info(text)
            ph_cmd1 = f"source {macro.DB_ENV_PATH}; cd $PGDATA; pagehack -f {res_path_st} -t ubtree_index"
            logger.info(ph_cmd1)
            res1 = self.userNode.sh(ph_cmd1).result()
            logger.info(res1)
            self.assertNotIn(f'pd_checksum: 0x0, verify fail', res1, '执行失败' + text)
            self.assertRegex(res1, r"pd_checksum: 0x[0-9a-fA-F]+, verify success", '执行失败' + text)
            self.assertNotIn(self.constant.NO_FILE_MSG, res1, '执行失败' + text)

    def tearDown(self):
        text = '--step6:清理环境，恢复默认值;expect:成功--'
        logger.info(text)
        data_cmd = self.comsh.execut_db_sql(self.prepare_data_00)
        logger.info(data_cmd)
        self.assertIn(self.constant.TABLE_DROP_SUCCESS, data_cmd, '执行失败' + text)
        logger.info(f'-----{os.path.basename(__file__)} end-----')
